// Copyright 2022 NullPTR. All Rights Reserved.


#include "TextLayoutUtils.h"


void FTextLayoutUtils::CalculateLayout(
	const FTextLayoutInfo& TextLayoutInfo,
	const TArray<FTextFontInfo>& TextFontInfo,
	bool VerticalLayout,
	TArray<FVector>& TextPosition, float* Width, float* Height)
{
	const int Num = TextFontInfo.Num();
	check(Num == TextPosition.Num());
	
	// 计算字符串总长
	float Length = 0;
	TArray<float> OriginOffsets;
	float LastActualAdvance = 0;
	for (int i = 0; i < Num; ++i)
	{
		//  计算字符尺寸
		float SelfActualAdvance;
		if (VerticalLayout)
		{
			SelfActualAdvance = TextFontInfo[i].AdvanceV * TextFontInfo[i].Height * TextLayoutInfo.KerningScale;
		}
		else
		{
			SelfActualAdvance = TextFontInfo[i].AdvanceH * TextFontInfo[i].Width * TextLayoutInfo.KerningScale;
		}

		// 计算OriginOffsets,前一个字符的后半部分加当前字符的前半部分
		if (i == 0)
		{
			OriginOffsets.Add(0.0);
		}
		else
		{
			OriginOffsets.Add(OriginOffsets[i - 1] + LastActualAdvance * 0.5 + SelfActualAdvance * 0.5);
		}

		// 计算字符串排列长度，第一个和最后一个字符只算半个
		// 只有一个字符的情况下，第一个和最后一个是同一个字符，因此下面的判断不能合并
		LastActualAdvance = SelfActualAdvance;
		Length += LastActualAdvance;
		if (i == 0)
		{
			Length -= LastActualAdvance * 0.5f;
		}
		if (i == Num - 1)
		{
			Length -= LastActualAdvance * 0.5f;
		}
	}

	// 居中
	const float HalfLength = Length / 2.0;
	for (int i = 0; i < Num; ++i)
	{
		if (VerticalLayout)
		{
			const auto Y = -HalfLength + OriginOffsets[i];
			const auto X = TextFontInfo[i].Width * TextFontInfo[i].AdvanceH * 0.5 - TextFontInfo[i].BitmapLeft;
			TextPosition[i] = FVector(TextLayoutInfo.AlignmentH, Y + TextLayoutInfo.AlignmentV, 0);
		}
		else
		{
			const auto X = -HalfLength + OriginOffsets[i];
			const auto Y = TextFontInfo[i].Height * TextFontInfo[i].AdvanceV * 0.5 - TextFontInfo[i].BitmapTop;
			TextPosition[i] = FVector(X + TextLayoutInfo.AlignmentH, Y + TextLayoutInfo.AlignmentV, 0);
		}
	}

	if (Width != nullptr)
	{
		*Width = Length;
	}

	if (Height != nullptr)
	{
		*Height = 0;
	}
}
